package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"tech-sys-manager/cache"
	"tech-sys-manager/models"
	"time"
)

func Detail(c *gin.Context) {
	id := c.Query("id")
	var detail models.Engin
	models.DB.Where("id = ?", id).First(&detail)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": detail,
	})
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.Engin{}).Count(&count)

	var list []models.Engin
	err := models.DB.Offset(offset).Limit(size).Find(&list).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"list":  list,
		},
	})
	return
}
func Lists(c *gin.Context) {
	var lists []models.Engin
	redis_key := "engin_lists"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&lists)
		jsonData, _ := json.Marshal(lists)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(cacheData), &lists)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": lists,
	})
}
